package com.atom.module.lib.opengles.ext

import android.opengl.Matrix
import android.util.Log
import com.atom.module.lib.opengles.GLModule


private fun FloatArray.checkSize() {
    if (size != 16) throw RuntimeException("Need a 16 values matrix.")
}

fun FloatArray.makeIdentity(): FloatArray {
    checkSize()
    Matrix.setIdentityM(this, 0)
    return this
}

fun FloatArray.clear(): FloatArray {
    return makeIdentity()
}

fun FloatArray.translate(x: Float = 0F, y: Float = 0F, z: Float = 0F): FloatArray {
    checkSize()
    Matrix.translateM(this, 0, x, y, z)
    return this
}

@Suppress("unused")
fun FloatArray.translateX(translation: Float): FloatArray {
    return translate(x = translation)
}

@Suppress("unused")
fun FloatArray.translateY(translation: Float): FloatArray {
    return translate(y = translation)
}

@Suppress("unused")
fun FloatArray.translateZ(translation: Float): FloatArray {
    return translate(z = translation)
}

fun FloatArray.scale(x: Float = 1F, y: Float = 1F, z: Float = 1F): FloatArray {
    checkSize()
    Matrix.scaleM(this, 0, x, y, z)
    return this
}

fun FloatArray.scaleX(scale: Float): FloatArray {
    return scale(x = scale)
}

fun FloatArray.scaleY(scale: Float): FloatArray {
    return scale(y = scale)
}

@Suppress("unused")
fun FloatArray.scaleZ(scale: Float): FloatArray {
    return scale(z = scale)
}

fun FloatArray.rotate(angle: Float, x: Float, y: Float, z: Float): FloatArray {
    checkSize()
    Matrix.rotateM(this, 0, angle, x, y, z)
    return this
}

fun FloatArray.rotateX(angle: Float): FloatArray {
    return rotate(angle = angle, x = 1F, y = 0F, z = 0F)
}


fun FloatArray.rotateY(angle: Float): FloatArray {
    return rotate(angle = angle, x = 0F, y = 1F, z = 0F)
}


fun FloatArray.rotateZ(angle: Float): FloatArray {
    return rotate(angle = angle, x = 0F, y = 0F, z = 1F)
}

fun FloatArray.print(): String {
    val builder = StringBuilder()
    builder.append("| ")
    builder.append(this.get(0)).append(" ,")
    builder.append(this.get(1)).append(" ,")
    builder.append(this.get(2)).append(" ,")
    builder.append(this.get(3))
    builder.append(" |\n")


    builder.append("| ")
    builder.append(this.get(0 + 4)).append(" ,")
    builder.append(this.get(1 + 4)).append(" ,")
    builder.append(this.get(2 + 4)).append(" ,")
    builder.append(this.get(3 + 4))
    builder.append(" |\n")


    builder.append("| ")
    builder.append(this.get(0 + 8)).append(" ,")
    builder.append(this.get(1 + 8)).append(" ,")
    builder.append(this.get(2 + 8)).append(" ,")
    builder.append(this.get(3 + 8))
    builder.append(" |\n")


    builder.append("| ")
    builder.append(this.get(0 + 12)).append(" ,")
    builder.append(this.get(1 + 12)).append(" ,")
    builder.append(this.get(2 + 12)).append(" ,")
    builder.append(this.get(3 + 12))
    builder.append(" |\n")
    return builder.toString()
}
